import { defineStore } from 'pinia';
import { localStorageGet, localStorageSet } from '@/utils/util.localStorage';

export const useThemeStore = defineStore('theme', () => {
	const theme = ref<'light' | 'dark'>('light');
	watch(theme, (val: 'light' | 'dark') => {
		localStorageSet('theme', val);
	});

	// 切换主题
	const toggleTheme = () => {
		theme.value = theme.value === 'light' ? 'dark' : 'light';
		document.documentElement.classList.toggle('dark');
	};

	onBeforeMount(() => {
		// 读取本地存储的主题
		const localTheme = localStorageGet('theme');
		if (localTheme) {
			theme.value = localTheme as 'light' | 'dark';
			document.documentElement.classList.add(theme.value);
		}
	});

	return {
		theme,
		toggleTheme,
	};
});
